package com.itxg.booksmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxg.booksmanage.entity.Book;
import com.itxg.booksmanage.entity.dto.BookPage;
import com.itxg.booksmanage.mapper.BookMapper;
import com.itxg.booksmanage.service.BookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public IPage<Book> getPageByCons(BookPage bookPage, Book book) {
        // 1.动态构建查询条件
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        // 书名、类型、作者
        wrapper.like(book.getBookName() != null, Book::getBookName, book.getBookName());
        wrapper.eq(book.getBookType() != null, Book::getBookType, book.getBookType());
        wrapper.like(book.getAuthor() != null, Book::getAuthor, book.getAuthor());
        Page<Book> pag = new Page<>();
        // 价格区间（有最小价格就选大于，有最大价格就选小于，有最高价最低价就选区间）
        wrapper.gt(bookPage.getMinPrice() != null, Book::getPrice, bookPage.getMinPrice());
        wrapper.lt(bookPage.getMaxPrice() != null, Book::getPrice, bookPage.getMaxPrice());
        // 2.根据时间戳字段进行排序
        wrapper.orderByDesc(Book::getCreateTime);
        // 3.传递当前页码（从 0 开始）、页大小，执行查询
        pag.setCurrent(bookPage.getPage() != null ? bookPage.getPage() : 0); // 设置默认值
        pag.setSize(bookPage.getPageSize() != null ? bookPage.getPageSize() : 10);
        IPage<Book> bookIPage = bookMapper.selectPage(pag, wrapper);
        // 3. 返回
        return bookIPage;
    }

    @Override
    public int updateBookById(Book book) {
        // 编辑之前将时间戳字段移除，即不设置更新时间字段
        return bookMapper.updateById(book) > 0 ? 1 : -1;
    }

    @Override
    public Book selectById(Integer id) {
        return bookMapper.selectById(211);
    }

    @Override
    public int deleteBookById(List<Integer> ids) {
        if (ids.size() <= 0) { // 参数不合法
            return -1;
        }
        int count = bookMapper.deleteBatchIds(ids); // 返回删除的记录数
        return count > 0 ? count : -1;
    }

    @Override
    public int addBook(Book book) {
        int i = bookMapper.insert(book);
        return i > 0 ? i : -1;
    }

}

